package com.hyq.grid.common;

import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by HYQ on 2020/7/5 20:55
 */
public class File_operation {
    /**
     * 写文件
     *
     * @param content 文件内容
     * @param path    存储地址
     */
    public static void WriteFile(String content, String path) {
        //win系统
//        String path = "c:\\hello.txt";
        File file = new File(path);
//        String content = "hello,shaonaiyi.";
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(content.getBytes());
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 写文件
     *
     * @param content      文件内容
     * @param path         存储地址
     * @param printSizeTag 是否存储打印信息
     * @throws IOException
     */
    public static void WriteFile(String content, String path, Boolean printSizeTag) throws IOException {
        //win系统
//        String path = "c:\\hello.txt";
        File file = new File(path);
//        String content = "hello,shaonaiyi.";
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(content.getBytes());
        if (printSizeTag)
            System.out.println("输出文件大小：" + file.length() + "字节");
        fileOutputStream.close();
    }

    /**
     * 读dat文件
     *
     * @param path 文件路径
     * @return 读取内容
     * @throws Exception
     */
    public static Map<String, Object> ReadFile(String path) throws Exception {
//        String path = "/Users/shaonaiyi/datas/tmp/hello.txt";
        //win系统
//        String path = "c:\\hello.txt";
        StringBuilder strBuilder = new StringBuilder("******node******\n");
        String printNode = "******node******\n";

        FileInputStream fileInputStream = new FileInputStream(path);

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));

        String line = null;

        Map<String, Object> Coordinates = new HashMap<String, Object>();
        List<Double[]> node = new ArrayList<>();
        List<Integer[]> element = new ArrayList<>();
        String[] temp;
        int printNodeIndex = 0;
        while ((line = bufferedReader.readLine()) != null) {
            if (line.contains("node ")) {

                temp = line.split("  | ");
                node.add(new Double[]{Double.parseDouble(temp[temp.length - 2]), Double.parseDouble(temp[temp.length - 1])});
                strBuilder.append(printNodeIndex + " " + Double.parseDouble(temp[temp.length - 2]) + " " + Double.parseDouble(temp[temp.length - 1]) + "\n");
                printNodeIndex++;
            } else if (line.contains("element ") && line.contains("-tria3 ")) {
                temp = line.split("  | ");
                element.add(new Integer[]{Integer.parseInt(temp[temp.length - 3]), Integer.parseInt(temp[temp.length - 2]), Integer.parseInt(temp[temp.length - 1])});
            } else if (line.contains("element ") && line.contains("-quad4 ")) {
                temp = line.split("  | ");
                element.add(new Integer[]{Integer.parseInt(temp[temp.length - 4]), Integer.parseInt(temp[temp.length - 3]), Integer.parseInt(temp[temp.length - 2]), Integer.parseInt(temp[temp.length - 1])});
            }

        }
        System.out.println(printNodeIndex);
        Coordinates.put("node", node);
        Coordinates.put("element", element);
        Coordinates.put("printNode", strBuilder);
        fileInputStream.close();
        return Coordinates;
    }

    /**
     * 读取文件
     *
     * @param path 文件地址
     * @return 返回读取的网格信息
     * @throws Exception
     */
    public static Map<String, Object> ReadFileNew(String path) throws Exception {
//        String path = "/Users/shaonaiyi/datas/tmp/hello.txt";
        //win系统
//        String path = "c:\\hello.txt";
        String printNode = "******node******\n";
        int printNodeIndex = 0;
        FileInputStream fileInputStream = new FileInputStream(path);

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));

        String line;

        Map<String, Object> Coordinates = new HashMap<String, Object>();
        List<double[]> node = new ArrayList<>();
        List<int[]> element = new ArrayList<>();
        String[] temp;
        while ((line = bufferedReader.readLine()) != null) {
            if (line.contains("node ")) {

                temp = line.split("  | ");

                node.add(new double[]{Double.parseDouble(temp[temp.length - 2]), Double.parseDouble(temp[temp.length - 1])});
                printNode += printNodeIndex + " " + Double.parseDouble(temp[temp.length - 2]) + " " + Double.parseDouble(temp[temp.length - 1]) + "\n";
                printNodeIndex++;

            } else if (line.contains("element ") && line.contains("-tria3 ")) {
                temp = line.split("  | ");
                element.add(new int[]{Integer.parseInt(temp[temp.length - 3]), Integer.parseInt(temp[temp.length - 2]), Integer.parseInt(temp[temp.length - 1])});
            } else if (line.contains("element ") && line.contains("-quad4 ")) {
                temp = line.split("  | ");
                element.add(new int[]{Integer.parseInt(temp[temp.length - 4]), Integer.parseInt(temp[temp.length - 3]), Integer.parseInt(temp[temp.length - 2]), Integer.parseInt(temp[temp.length - 1])});
            }

        }
        Coordinates.put("node", node);
        Coordinates.put("element", element);
        Coordinates.put("printNode", printNode);
        fileInputStream.close();
        return Coordinates;
    }

    /**
     * 删除文件
     *
     * @param path 文件路径
     * @return
     */
    public static boolean deleteFile(String path) {
        boolean flag = false;
        File file = new File(path);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 获取不带扩展名的扩展名文件名
     *
     * @param filename
     * @return 返回不带扩展名的文件名，如果没有获取到返null
     */
    public static String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return null;
    }

    /**
     * 获取文件的扩展名
     *
     * @param filename
     * @return 返回文件的扩展名，如果没有获取到返null
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(dot + 1);
            }
        }
        return null;
    }

    /**
     * 上传文件
     *
     * @param file       上传的文件
     * @param upLoadPath 保存的静态地址
     * @param req        请求头信息
     * @return 返回文件信息及url访问地址
     */
    public static Map<String, Object> upload(MultipartFile file, String upLoadPath, HttpServletRequest req) {
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        Map<String, Object> result = new HashMap<>();
        String originName = file.getOriginalFilename();
        String fikeExtensionName = File_operation.getExtensionName(originName);
        if (!fikeExtensionName.equals("txt")) {
            result.put("statu", "error");
            result.put("msg", "文件类型不对");
            return result;
        }


        String format = sdf.format((new Date()));
        String realPath = upLoadPath + format;

        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String newName = UUID.randomUUID().toString() + "." + fikeExtensionName;
        System.out.println("文件上传至：" + realPath + newName);

        try {
            file.transferTo(new File(folder, newName));
            List<Double[]> border = parseUploadTxtFile(realPath + newName);
            String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + format + newName;

            result.put("statu", "success");
            result.put("border", border);
            result.put("url", url);
        } catch (IOException e) {
            result.put("statu", "error");
            result.put("msg", e.getMessage());
        }
        return result;
    }

    /**
     * 解析上传的文件
     *
     * @param filePath 文件上传的地址
     * @return 返回上传的坐标信息
     */
    public static List<Double[]> parseUploadTxtFile(String filePath) {
        List<Double[]> borderPoints = new ArrayList<>();
        try {
            FileInputStream fileInputStream = new FileInputStream(filePath);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
            String line;
            String[] temp;

            while ((line = bufferedReader.readLine()) != null) {
                temp = line.split("  | ");

                Double[] point = new Double[]{Double.parseDouble(temp[temp.length - 2]), Double.parseDouble(temp[temp.length - 1])};
                borderPoints.add(point);
            }
        } catch (FileNotFoundException e) {
            System.out.println("文件打开失败！");
            System.out.println(e.getMessage());
            return null;
        } catch (IOException e) {
            System.out.println("文件读取失败！");
            System.out.println(e.getMessage());
            return null;
        }


        return borderPoints;
    }

    /**
     * 解析DAT文件
     *
     * @param path          文件路径
     * @param nodeDimension 点坐标维度 2: (x,y) 3: (x,y,z)
     * @param nodeCount     每个网格单元包含的节点数 三角形: 3 四边形: 4 四面体: 4 ...
     * @return 读取的文件信息 {List<Double[]> node: [[x1,y1],[],[]...], List<Integer[]> element: [[node1_index,node2_index...],[],[]] }
     * @throws Exception
     */
    public static Map<String, Object> parseDatFile(String path, int nodeDimension, int nodeCount) throws Exception {

        StringBuilder strBuilder = new StringBuilder("******node******\n");
        String printNode = "******node******\n";

        FileInputStream fileInputStream = new FileInputStream(path);

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));

        String line = null;

        Map<String, Object> Coordinates = new HashMap<String, Object>();
        List<Double[]> node = new ArrayList<>();
        List<Integer[]> element = new ArrayList<>();
        String[] temp;
        int printNodeIndex = 0;
        while ((line = bufferedReader.readLine()) != null) {
            if (line.contains("node ")) {
                temp = line.split("  | ");
                Double[] tempNodeCoor = new Double[nodeDimension];

                strBuilder.append(printNodeIndex);
                for (int i = 0; i < tempNodeCoor.length; i++) {
                    tempNodeCoor[tempNodeCoor.length - 1 - i] = Double.parseDouble(temp[temp.length - i - 1]);
                    strBuilder.append(" " + Double.parseDouble(temp[temp.length - i - 1]));
                }
                node.add(tempNodeCoor);
                strBuilder.append("\n");
                printNodeIndex++;
            } else if (line.contains("element ")) {
                temp = line.split("  | ");
                Integer[] tempElement = new Integer[nodeCount];
                for (int i = 0; i < tempElement.length; i++) {
                    tempElement[tempElement.length - 1 - i] = Integer.parseInt(temp[temp.length - i - 1]) - 1;
                }
                element.add(tempElement);
            }

        }

        Coordinates.put("node", node);
        Coordinates.put("element", element);
        Coordinates.put("printNode", strBuilder);
        fileInputStream.close();
        return Coordinates;
    }

    /**
     * 解析MSH文件
     *
     * @param path
     * @return 返回读取的坐标信息和网格单元信息
     * @throws IOException
     */
    public static Map<String, Object> ParseMshFile(String path) throws IOException {
        StringBuilder strBuilder = new StringBuilder("******node******\n");
        String printNode = "******node******\n";

        FileInputStream fileInputStream = new FileInputStream(path);

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));

        String line = null;

        Map<String, Object> Coordinates = new HashMap<String, Object>();
        List<Double[]> node = new ArrayList<>();
        List<Integer[]> element = new ArrayList<>();
        String[] temp;
        int printNodeIndex = 0;

        boolean nodeTag = false;
        boolean elementTag = false;

        int num = 0;// 一次读取多少个坐标
        int readtag = 0;
        boolean groupTag = false;
        while ((line = bufferedReader.readLine()) != null) {
            if (line.contains("$Nodes")) {
                nodeTag = true;
                groupTag = true;
                continue;
            } else if (line.contains("$EndNodes")) {
                nodeTag = false;
                num = 0;
                readtag = 0;
                groupTag = false;
            } else if (line.contains("$Elements")) {
                elementTag = true;
                groupTag = true;
                continue;
            } else if (line.contains("$EndElements")) {
                break;
            }

            if (nodeTag) {
                if (groupTag) {
                    groupTag = false;
                    continue;
                }
                if (num == 0) {
//                    获取读取坐标对数量
                    temp = line.split("  | ");
                    num = Integer.parseInt(temp[temp.length - 1]);
                    readtag = Integer.parseInt(temp[temp.length - 1]);
                    continue;
                } else {
                    if (readtag == 0) {
//                        跳过索引后开始读取坐标
                        temp = line.split("  | ");
                        node.add(new Double[]{Double.parseDouble(temp[temp.length - 3]), Double.parseDouble(temp[temp.length - 2]), Double.parseDouble(temp[temp.length - 1])});
                        num--;
                    } else {

                        //跳过索引
                        readtag--;
                        continue;
                    }

                }
            }

            if (elementTag) {
                if (groupTag) {
                    groupTag = false;
                    continue;
                }
                if (num == 0) {
//                    获取读取坐标对数量
                    temp = line.split("  | ");

                    num = Integer.parseInt(temp[temp.length - 1]);

                    continue;
                } else {

//                    开始读取坐标点索引
                    num--;
                    temp = line.split("  | ");
                    if (temp.length < 5) continue;
                    element.add(new Integer[]{Integer.valueOf(temp[temp.length - 4]), Integer.valueOf(temp[temp.length - 3]), Integer.valueOf(temp[temp.length - 2]), Integer.valueOf(temp[temp.length - 1])});


                }
            }

        }
        System.out.println(printNodeIndex);
        Coordinates.put("node", node);
        Coordinates.put("element", element);
        Coordinates.put("printNode", strBuilder);
        fileInputStream.close();
        return Coordinates;

    }


}
